<?php

namespace app\admin\service;

use app\admin\validate\Login;
use app\common\configs\SettingConf;
use app\common\model\trAdmin;
use app\common\model\trAdminSession;
use app\saas\model\trMall;
use app\common\model\trResource;
use app\common\model\trSystemSet;
use app\common\util\ErrorCode;
use app\common\util\Tools;

/**
 * Class Auth
 * @package app\admin\service
 * 登录服务类
 */
class LoginService
{
    private $params;
    private $returnData;
    private $mall_id = 0;

    public function __construct($data, $params)
    {
        $this->returnData = $data;
        $this->params = $params;
        $this->mall_id = request()->mallData["id"];
    }

    // 账号密码登录
    public function LoginByAccount(){
        if(!empty($this->params["wsToken"])){
            $domain = isset($this->params["wsDomain"]) ? urldecode($this->params["wsDomain"]) : "https://wx.wegouer.com/terrace/index.php";
            $res = Tools::curl($domain."/web/home/getCheckToken", json_encode(["wsToken" => $this->params["wsToken"]]));
            $res = json_decode($res, true);
            if($res["code"] == "0"){
                $data = trAdmin::where("type", 1)->field("id,username,type,status,expired_time,password,salt")->find();
                $data = $data ? Tools::transferFields($data->toArray()) : [];
            }else{
                $this->returnData = ErrorCode::code('token_expire');
                $this->returnData["msg"] = "自动登录失败";
                return $this->returnData;
            }
        }else {
            $admin = new Login();
            if (!$admin->check($this->params)) {
                $this->returnData = ErrorCode::$errorCode['params_error'];
                $this->returnData['msg'] = $admin->getError();
                return $this->returnData;
            }
            $data = trAdmin::getAdminInfo($this->params['username'], "id,username,type,status,expired_time,password,salt");
        }
        if (!empty($data)) {
            if(isset($this->params['password']) && $data['password'] != generate_password($this->params['password'], $data["salt"])) {
                $this->returnData = ErrorCode::code("account_error");
                return $this->returnData;
            }
            if($data["type"] != "1" && !empty($data["expiredTime"]) && $data["expiredTime"] <= time()){
                return ErrorCode::code('account_expired');
            }
            if($data["status"] == "3"){
                return ErrorCode::code('customized', "账号已被删除，请联系管理员");
            }elseif($data["status"] == "2"){
                $this->returnData = ErrorCode::code('account_disable');
            }else {
                $sessionId = trAdmin::generateSessionId();
                $data["loginIp"] = Tools::get_client_ip();
                $data["isAdmin"] = "1"; // 商城已登陆
                $data["tokenTime"] = time() + config("session_expire");
                //保存token
                $result = trAdminSession::add([
                    "admin_id" => $data['id'], "session_id" => $sessionId, "login_ip" => $data["loginIp"], "create_time" => time(),
                    "expire_time" => $data["tokenTime"], "is_admin" => $data["isAdmin"]
                ]);
                if (isset($result['code'])) {
                    return $result;
                }
                unset($data["password"], $data["salt"]);
                cache("admin_" . $sessionId, $data, config("session_expire")); //缓存用户信息
                $mallData = trMall::getFields("id,name", ["manager_id" => $data["id"], "is_disable" => 0, "is_delete" => 0], true, false);
                if(empty($mallData)){
                    $mallData = trMall::getFields("id,name", ["manager_id" => $data["id"]], true, false);
                }
                $this->returnData['data'] = ['token' => $sessionId, "mall" => $mallData];
            }
        } else {
            $this->returnData = ErrorCode::code("account_not_exist");
        }
        return $this->returnData;
    }

    /**
     * @param $sessionId
     * @return bool|mixed
     * 判断sessionID是否有效
     */
    public static function checkSession($sessionId){
        if (!$adminData = cache("admin_" . $sessionId)) {
            if (empty($data = trAdminSession::getFields("expire_time,admin_id,login_ip,is_admin,is_saas", ["session_id" => $sessionId], true, false))) {
                return false;
            }
            if (time() > $data["expireTime"]) { //sessionId过期了
                return false;
            }
            if($data["isAdmin"] == "3"){ // 已退出了
                if($data["isSaas"] == "1"){ // SaaS端还登录着
                    trAdminSession::doUpdate(["is_admin" => "1"], ["session_id" => $sessionId]);
                }else {
                    return false;
                }
            }
            if (!empty($adminData = trAdmin::getAdminInfo($data['adminId'], "id,username,type,status,expired_time"))) {
                $adminData["loginIp"] = $data["loginIp"];
                $adminData["isAdmin"] = "1";
                $adminData["tokenTime"] = $data["expireTime"]; // token时间
                if($data["isAdmin"] == "0"){ // 未登陆，改成登陆
                    trAdminSession::doUpdate(["is_admin" => "1"], ["session_id" => $sessionId]);
                }
                cache("admin_" . $sessionId, $adminData, $data["expireTime"] - time());
            } else {
                return ErrorCode::code("account_not_exist");
            }
        }else{
            if ($adminData["isAdmin"] == "3") { // 退出了
                return false;
            }
            if ($adminData["isAdmin"] == "0") { // SaaS未登陆
                trAdminSession::doUpdate(["is_admin" => "1"], ["session_id" => $sessionId]);
                $adminData["isAdmin"] = "1";
                cache("admin_" . $sessionId, $adminData, $adminData["tokenTime"] - time());
            }
        }
        if($adminData["type"] != "1"){ // 不是超管，要判断账号是否到期等等
            if($adminData["status"] == "2"){
                return ErrorCode::code('account_disable');
            }
            if($adminData["status"] == "3"){
                return ErrorCode::code('customized', "账号已被删除，请联系管理员");
            }
            if(!empty($adminData["expiredTime"]) && $adminData["expiredTime"] <= time()){
                return ErrorCode::code('account_expired');
            }
        }
//        if(isset($data["loginIp"]) && ($data["loginIp"] != Tools::get_client_ip())){
//            $this->returnData =   ErrorCode::code("ip_token_error");
//            return false;
//        }
        return $adminData;
    }

    //清除登录token
    public function clearSession($id, $sessionId){
        if(empty($id) && empty($sessionId)){
            return true;
        }
        trAdminSession::doUpdate(["is_admin" => "3"], ["admin_id" => $id, "session_id" => $sessionId]);
        if (!$adminData = cache("admin_" . $sessionId)) {
            cache("admin_" . $this->params['token'], null);
        }
        return true;
    }

    //登录者信息
    public function getLoginInfo($admin_id){
        $data = trAdmin::getAdminInfo($admin_id);
        if($data){
            if(empty($data["expiredTime"])){
                $data["expiredTime"] = "永久";
            }else{
                $data["expiredTime"] = date("Y-m-d H:i:s", $data["expiredTime"]);
            }
            $data["isSuper"] = $data["type"] == '1' ? true : false; // 1 - 超级管理员 | 其它 - 普通管理员
            $data['avatar'] = tome_dia(!empty($data['avatar']) ? trResource::getValue("url", ["id" => $data["avatar"]]) : "/attachment/default/n1wAgn1jD8GnNQ1LnWd8j1W8898nGL.png");
            unset($data['password']);
            unset($data['salt']);
        }
        $mallData = trMall::getFields("id as mallId", ["manager_id" => $data["id"], "is_disable" => 0, "is_delete" => 0], true, false);
        if(empty($mallData)){
            $mallData = trMall::getFields("id as mallId", ["manager_id" => $data["id"]], true, false);
        }
        if(is_array($mallData)){
            $data = array_merge($data, $mallData);
        }
        $this->returnData['data'] = $data;
        return $this->returnData;
    }

    //退出登陆
    public function logout($admin_id)
    {
        $this->clearSession($admin_id, $this->params['token']);
        return $this->returnData;
    }

    //登录页的配置
    public function getConfig()
    {
        $data = trSystemSet::getValue(SettingConf::LOGIN_CONFIG);
        foreach (SettingConf::$baseConfigArr[SettingConf::LOGIN_CONFIG] as $field => $value) {
            if(!isset($data[$field])){
                $data[$field] = $value;
            }
        }
        $this->returnData['data'] = $data;
        return $this->returnData;
    }
}